package com.tongshu.naive.chat;

import com.tongshu.naive.chat.domain.user.service.UserServiceImpl;
import com.tongshu.naive.chat.socket.NettyServer;
import io.netty.channel.Channel;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

import javax.annotation.Resource;
import java.util.concurrent.*;

@SpringBootApplication
@Configuration
@ImportResource(locations = {"classpath:spring-config.xml"})
@MapperScan("com.tongshu.naive.chat.infrastructure.dao")
public class Application extends SpringBootServletInitializer implements CommandLineRunner {

    private Logger logger = LoggerFactory.getLogger(Application.class);
    @Resource
    private NettyServer nettyServer;
    private ExecutorService executorService = new ThreadPoolExecutor(2, 4, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }

    @Override
    public void run(String... args) throws Exception {
        /**
         * 服务启动时执行的操作：以多线程方式启动NettyServer
         */
        logger.info("NettyServer启动服务开始 port：7397");
        Future<Channel> channelFuture = executorService.submit(nettyServer);
        Channel channel = channelFuture.get();
        if (null == channel) throw new RuntimeException("netty server start error channel is null");
        while (!channel.isActive()) {
            logger.info("NettyServer启动服务 ...");
            TimeUnit.MILLISECONDS.sleep(500);
        }

        logger.info("NettyServer启动服务完成 {}", channel.localAddress());
    }
}
